import 'package:flutter/material.dart';
import '../../../app_files.dart';
import 'package:fish_redux/fish_redux.dart';
import '../engineer_gas_view/action.dart';
import 'dart:io';

class NormalConfigModel {
  final String configName;
  final String configID;
  final List<String> configContent;
  TextEditingController textEditingController = TextEditingController();

  bool get hasOther => uploadContent.contains(valueDesc);
  String valueDesc = '';
  final bool isRemind;
  final List<String> inputContent;
  final List<String> uploadContent;
  final List<String> infoContent;
  final List<String> values = [];
  List imageList = [];
  Map infoValues = {};

  String get valueStr {
    if (isRemind == true) {
      return '完成';
    }

    if (infoContent.isNotEmpty) {
      List<String> items = infoContent
          .map<String>((e) =>
              '$e：${CommonUtils.checkNullToString(infoValues[e]).isEmpty ? '无' : CommonUtils.checkNullToString(infoValues[e])}')
          .toList();
      return items.join('\r\n');
    }

    if (hasOther == true)
      return textEditingController.text.isEmpty
          ? valueDesc
          : '$valueDesc：${textEditingController.text}';
    if (inputContent.contains(valueDesc))
      return '$valueDesc：${textEditingController.text}';
    return valueDesc;
  }

  NormalConfigModel({
    this.configContent,
    this.configID,
    this.configName,
    this.isRemind,
    this.imageList,
    this.valueDesc = '',
    this.inputContent = const [],
    this.uploadContent = const [],
    this.infoContent = const [],
  });

  static fromJson(json) {
    List configValue = json['ConfigContent'] ?? [];
    List<String> configs = configValue
        .map<String>((e) => CommonUtils.checkNullToString(e))
        .toList();
    List inputContent = json['inputContent'] ?? [];
    List<String> inputValues = inputContent
        .map<String>((e) => CommonUtils.checkNullToString(e))
        .toList();

    List uploadContent = json['uploadContent'] ?? [];
    List<String> uploadValues = uploadContent
        .map<String>((e) => CommonUtils.checkNullToString(e))
        .toList();

    List infoContent = json['infoContent'] ?? [];
    List<String> infoValues = infoContent
        .map<String>((e) => CommonUtils.checkNullToString(e))
        .toList();

    return NormalConfigModel(
      configID: CommonUtils.checkNullToString(json['ConfigId']),
      configName: CommonUtils.checkNullToString(json['ConfigName']),
      configContent: configs,
      isRemind: json['isRemind'] ?? false,
      imageList: [],
      inputContent: inputValues,
      uploadContent: uploadValues,
      infoContent: infoValues,
    );
  }

  static fromResultJson(json) {
    return NormalConfigModel(
      configID: CommonUtils.checkNullToString(json['ConfigId']),
      configName: CommonUtils.checkNullToString(json['ConfigKey']),
      imageList: json['ImageList'] ?? [],
      valueDesc: CommonUtils.checkNullToString(json['ConfigValue']),
      isRemind: false,
    );
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['ConfigId'] = this.configID;
    data['ConfigKey'] = this.configName;
    data['ImageList'] = this.imageList;
    data['ConfigValue'] = this.valueStr;
    return data;
  }

  setSaveContent(List itemJson) {
    for (var json in itemJson) {
      if (json['ConfigId'] == configID) {
        List images = json['ImageList'] ?? [];
        imageList.addAll(images);
        List<String> values =
            CommonUtils.checkNullToString(json['ConfigValue']).split('：');
        valueDesc = values.first;
        if (values.length > 1) {
          textEditingController.text = values[1];
        }
        return;
      }
    }
  }
}

const double kImageWidth = 90;
const double kTextFieldHeight = 70;

class NormalConfigWidget extends StatelessWidget {
  final NormalConfigModel model;
  final void Function(
    String type,
    NormalConfigModel model, {
    dynamic file,
  }) onTap;

  // final Dispatch dispatch;

  const NormalConfigWidget(this.model, this.onTap);

  Widget _selectWidget(String value) {
    bool isSelect = model.values.contains(value);
    return InkWell(
      child: Container(
        color: Colors.white,
        padding: EdgeInsets.only(top: 8, bottom: 8),
        child: Row(
          children: [
            Expanded(
              child: Container(
                padding: EdgeInsets.only(right: 12),
                child: Text(
                  value,
                  style: TextThemeConfig.Font14WithColor22,
                ),
              ),
            ),
            Container(
              width: 19,
              child: Center(
                child: Image.asset(isSelect
                    ? 'images/icon_select.png'
                    : 'images/icon_normal.png'),
              ),
            )
          ],
        ),
      ),
      onTap: () {
        if (model.values.contains(value)) {
          model.values.remove(value);
        } else {
          model.values.add(value);
        }
        onTap('refresh', model);
      },
    );
  }

  Widget _itemWidget(String value) {
    bool isSelect = model.valueDesc == value;
    return InkWell(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
        child: Text(
          value,
          style: !isSelect
              ? TextThemeConfig.Font13WithColor66
              : TextThemeConfig.Font13WithColorblue,
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(2)),
          color: isSelect ? Color(0xffE6EEFF) : Color(0xffF5F5F5),
        ),
      ),
      onTap: () {
        // model.hasOther = false;
        model.valueDesc = value;
        onTap('refresh', model);
      },
    );
  }

  Widget _otherWidget() => InkWell(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
          child: Text(
            '其他问题',
            style: !model.hasOther
                ? TextThemeConfig.Font13WithColor66
                : TextThemeConfig.Font13WithColorblue,
          ),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(2)),
            color: !model.hasOther ? Color(0xffF5F5F5) : Color(0xffE6EEFF),
          ),
        ),
        onTap: () {
          // model.hasOther = true;
          onTap('refresh', model);
        },
      );

  Widget _imageWidget() => Container(
        margin: EdgeInsets.only(top: 20),
        height: kImageWidth,
        child: ListView.builder(
          itemBuilder: (BuildContext context, int index) {
            if (index == model.imageList.length) {
              return InkWell(
                  child: Container(
                    margin: EdgeInsets.only(right: 12),
                    width: kImageWidth,
                    height: kImageWidth,
                    color: Color(0xffF5F5F5),
                    child: Align(
                      child: Image.asset('images/icon_camera.png'),
                    ),
                  ),
                  onTap: () => onTap('onAddPic', model));
            } else {
              var file = model.imageList[index];
              return InkWell(
                child: Container(
                  margin: EdgeInsets.only(right: 12),
                  width: kImageWidth,
                  height: kImageWidth,
                  child: CustomImage(
                    file,
                    width: kImageWidth,
                    height: kImageWidth,
                    fit: BoxFit.fill,
                  ),
                ),
                onTap: () => onTap('onTapPic', model, file: file),
              );
            }
          },
          itemCount: model.imageList.length + 1,
          scrollDirection: Axis.horizontal,
          itemExtent: kImageWidth + 12,
          padding: EdgeInsets.only(),
        ),
      );

  Widget _editWidget() => Container(
        margin: EdgeInsets.only(top: 12),
        height: kTextFieldHeight,
        child: TextField(
          minLines: 1,
          maxLines: 10,
          controller: model.textEditingController,
          style: TextThemeConfig.Font13WithColor22,
          decoration: InputDecoration(
            border: InputBorder.none,
            hintText: "请在此处描述问题...",
            hintStyle: TextThemeConfig.Font13WithColor99,
            contentPadding: EdgeInsets.only(),
          ),
          onChanged: (String str) {
            if (str.length > ThemeConfig.descTextLength)
              model.textEditingController.text =
                  str.substring(0, ThemeConfig.descTextLength);
          },
        ),
      );

  Widget _inputWidget() => Container(
        margin: EdgeInsets.only(top: 6, left: 5),
        height: 30,
        child: TextField(
          minLines: 1,
          maxLines: 10,
          controller: model.textEditingController,
          style: TextThemeConfig.Font13WithColor22,
          decoration: InputDecoration(
            border: InputBorder.none,
            hintText: "请填写",
            hintStyle: TextThemeConfig.Font13WithColor99,
            contentPadding: EdgeInsets.only(bottom: 13),
          ),
          onChanged: (String str) {
            if (str.length > ThemeConfig.descTextLength)
              model.textEditingController.text =
                  str.substring(0, ThemeConfig.descTextLength);
          },
        ),
      );

  @override
  Widget build(BuildContext context) {
    Widget _contentWidget() {
      if (model.infoContent.isNotEmpty) {
        List<Widget> widgets = model.infoContent
            .map((e) => Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '$e :',
                      style: TextThemeConfig.Font15WithColor22,
                    ),
                    Expanded(
                      child: Container(
                        margin: EdgeInsets.only(left: 12),
                        height: 30,
                        child: TextField(
                          minLines: 1,
                          maxLines: 10,
                          style: TextThemeConfig.Font13WithColor22,
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            hintText: "请填写",
                            hintStyle: TextThemeConfig.Font14WithColor99,
                            contentPadding: EdgeInsets.only(bottom: 15),
                          ),
                          onChanged: (String str) {
                            if (str.length < ThemeConfig.descTextLength)
                              model.infoValues[e] = str;
                          },
                        ),
                      ),
                    ),
                  ],
                ))
            .toList();
        return Padding(
          padding: EdgeInsets.only(
            top: 4,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: widgets,
          ),
        );
      }
      if (model.isRemind) {
        List<Widget> items =
            model.configContent.map((e) => _selectWidget(e)).toList();
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: items,
        );
      } else {
        List<Widget> items =
            model.configContent.map((e) => _itemWidget(e)).toList();
        // items.add(_otherWidget());
        return Padding(
          padding: EdgeInsets.only(top: 12, bottom: 8),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Wrap(
                spacing: 20.0, // 主轴(水平)方向间距
                runSpacing: 15.0, // 纵轴（垂直）方向间距
                alignment: WrapAlignment.start,
                children: items,
              ),
              model.hasOther
                  ? _editWidget()
                  : model.inputContent.contains(model.valueDesc)
                      ? _inputWidget()
                      : Container(),
              model.hasOther ? _imageWidget() : Container(),
            ],
          ),
        );
      }
    }

    return Container(
      padding: EdgeInsets.only(left: 15, right: 15, bottom: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
            bottom: BorderSide(color: ThemeConfig.separeColor, width: 10)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            height: 44,
            child: Align(
              alignment: Alignment.centerLeft,
              child: Text(
                model.configName,
                style: TextThemeConfig.Font16WithColorBold22,
              ),
            ),
            margin: EdgeInsets.only(bottom: 4),
            decoration: BoxDecoration(
                border:
                    Border(bottom: BorderSide(color: ThemeConfig.separeColor))),
          ),
          _contentWidget(),
        ],
      ),
    );
  }
}
